package com.exp.bookhouse.aspect;

import com.exp.bookhouse.pojo.SysLog;
import com.exp.bookhouse.pojo.myUser;
import com.exp.bookhouse.service.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


//使用切面对后端管理访问接口进行日志处理，写到log文件中
@Component
@Aspect
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Date visitTime; // 访问时间


    @Pointcut("execution(* com.exp.bookhouse.controller.admin.*.*(..))")
    public void sysLog(){}


    //前置通知
    @Before("sysLog()")
    public void doBefore(){
        visitTime = new Date(); //访问时间
    }


    //后置通知
    @After("sysLog()")
    public void doAfter(JoinPoint joinPoint){
        //获取request对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String url = request.getRequestURL().toString();    //访问资源url
        String ip = request.getRemoteAddr();    //访问ip
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();    //方法
        long executionTime = System.currentTimeMillis() - visitTime.getTime();    //执行时长
        myUser myUser = (myUser) request.getSession().getAttribute("user");
        if(myUser == null) {
            return;
        }
        String loginUser = myUser.getLoginUser();     //访问者

        //自身不记录
        if("SysLogControllerAdmin.toSysLog".equals(classMethod)){
            return;
        }

        SysLog sysLog = new SysLog();
        sysLog.setVisitTime(visitTime);
        sysLog.setUrl(url);
        sysLog.setIp(ip);
        sysLog.setMethod(classMethod);
        sysLog.setLoginUser(loginUser);
        sysLog.setExecutionTime(executionTime);

        //记录日志文件
        logger.info("sysLog：{}",sysLog);

        //保存到数据库
        sysLogService.saveSysLog(sysLog);
    }

}
